package com.lry.basic.jvm.asm.transform_class.demo20;

import com.itranswarp.compiler.JavaStringCompiler;
import com.lry.basic.jvm.asm.utils.FileUtils;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Map;

public class Test {



    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();
        String relative_path = "com/lry/basic/jvm/asm/transform_class/demo20/CalPointsImpl.java";
        String filepath = FileUtils.getFilePath(relative_path);

        String code = "package com.lry.basic.jvm.asm.transform_class.demo20;\n" +
                "\n" +
                "public class CalPointsImpl implements CalPoints{\n" +
                "    @Override\n" +
                "    public long calPoints(long points) {\n" +
                "        points = points*2;\n" +
                "        return points;\n" +
                "    }\n" +
                "}\n";

        File file = FileUtils.writeBytes(filepath,code.getBytes());
//        File file = new File(filepath);
        try {
            //编译
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null,null);
            Iterable units = fileManager.getJavaFileObjects(file);
            JavaCompiler.CompilationTask t = compiler.getTask(null, fileManager, null, null, null, units);
            t.call();
            fileManager.close();

            Class clazz = Class.forName("com.lry.basic.jvm.asm.transform_class.demo20.CalPointsImpl");

            Object obj = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("calPoints",long.class);
            System.out.println(method.invoke(obj, 1));
            System.out.println(System.currentTimeMillis()-start);

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
